package jt.com.jt809.manage;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Tcp服务连接数、缓存管理
 *
 * @Author OuJiaJun
 * @Date 2024/4/24 10:36
 */
@Slf4j
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class TcpChannelMsgManage {

    @Value("${server.port}")
    private String serverPort;

    /**
     * 缓存本地ip地址信息，避免每次都重新调用系统函数
     */
    private static final Map<String, String> HOST_MAP = new ConcurrentHashMap<String, String>();

    /**
     * 客户端连接计数器 单点
     */
    private static final AtomicInteger TCP_CLIENT_CONNECT_NUM = new AtomicInteger(0);


    /**
     * 获取本机ip信息
     */
    public String getLocalhostInfo() {
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
            return addr.getHostAddress();
        } catch (UnknownHostException e) {
            log.error("获取本机ip失败", e);
        }
        return null;
    }

    /**
     * 获取本机ip + 服务端口
     */
    public String getIpAndPort() {
        String localhost = HOST_MAP.get("localhost");
        if (localhost != null) {
            return localhost;
        }
        localhost = this.getLocalhostInfo() + ":" + serverPort;
        HOST_MAP.put("localhost", localhost);
        return localhost;
    }


    /**
     * 获取当前节点的 TCP 连接数
     */
    public int getTcpClientConnectNum() {
        return TCP_CLIENT_CONNECT_NUM.get();
    }

    /**
     * 当前节点 TCP 连接数 递增
     */
    public void incrementTcpClientConnectNum() {
        TCP_CLIENT_CONNECT_NUM.getAndIncrement();
    }

    /**
     * 当前节点 TCP 连接数 递减
     */
    public void decrementTcpClientConnectNum() {
        TCP_CLIENT_CONNECT_NUM.getAndDecrement();
    }
}
